<?php
class GroupModel extends RelationModel
{
	public $_link = array (
	
	 'founder' => array(   
 					'mapping_type'=>BELONGS_TO, 
                    'class_name'=>'user', 
                    'foreign_key'=>'founder_id', 
                    'mapping_name'=>'founder',
                   )
	);
	
	public function found($founder_id,$group_name, $introduction) {
		$group['name'] = $group_name;
		$group['introduction'] = $introduction;
		$group['founder_id'] = $founder_id;
		$group['create_time'] = time();
		$group_id = $this->add($group);
		$group_user_dao = M('groupUser');
		$group_user_relation['group_id'] = $group_id;
		$group_user_relation['user_id'] = $founder_id;
		$group_user_dao->add($group_user_relation);
	}
	
	public function getAll($record_num)
	{
		import("ORG.Util.Page"); //  导入分页类 
	 	$count = $this->count();
	 	$Page = new Page ( $count, $record_num );
	 	$show = $Page->show (); //  分页显示输出 
	 	$groups = $this->relation('founder')
			->order('create_time desc')
			->limit ( $Page->firstRow.','.$Page->listRows )->select();
		$result = array('data'=>$groups,'page'=>$show);
	 	return $result;
	}
	
	public function getGroupIdsByUserId($user_id)
	{
		$condition['user_id'] = $user_id;
		$group_dao_dao = M('groupUser');
		$group_user_relations = $group_dao_dao->where($condition)->select();
		foreach ($group_user_relations as $relation) {
			$group_ids[] = $relation['group_id'];
		}
		return $group_ids;
	}
	
	public function getById($group_id) {
		$condition['id'] = $group_id;
		$group = $this->where($condition)->relation(true)->find();
		$group_user_dao = M('groupUser');
		$condition2['group_id'] = $group_id;
		$relations = $group_user_dao->where($condition2)->select();
		$user_dao = new UserModel();
		foreach ($relations as $relation) {
			$group['members'][] = $user_dao->getById($relation['user_id']);
		}
		
		return $group;
	}
	
	public function getNewestGroups($num) {
		$groups = $this->relation(true)
			->order("create_time desc")->limit($num)->select();
		
		return $groups;
	}
	
	
	public function deleteMemeber($group_id, $member_id) {
		$group_user_dao = M('groupUser');
		$condition['group_id'] = $group_id;
		$condition['user_id'] = $member_id;
		$group_user_dao->where($condition)->delete();
	}
	
	public function getByUserId($user_id) {
		$condition['founder_id'] = $user_id;
		$groups = $this->where($condition)->relation(true)->select();
		return $groups;
	}
}

?>